package com.yfbao.poll.demo.model;

import com.yfbao.poll.demo.service.PollingCache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.LockSupport;

/**
 * 同步长轮询
 */
public class SyncLongPoll extends BasePoll {

    private static final Log logger = LogFactory.getLog(SyncLongPoll.class);

    public SyncLongPoll(Thread thread, Map<String, Long> userMsgTypes, String userName, long timeoutTime, String tag) {
        super(userMsgTypes,userName,timeoutTime,tag,false);
        this.thread =thread;
    }

    //当前线程
    final Thread thread;


    @Override
    public String toString() {
        return "SyncLongPoll{" + "clientListenMsgMap=" + userMsgTypes + ", createTime=" + createTime + ", user='" + userName
                + '\'' +  ", tag='" + tag + '\'' + ", timeoutTime=" + timeoutTime + ", isAsync=" + isAsync +'}';
    }

    public void removeFutureTaskAndUnpark() {
        LockSupport.unpark(this.thread);
    }

    public void addWebPollRequest() {
        List<BasePoll> basePolls = PollingCache.getAllWebMap().get(userName);
        if(basePolls ==null){
            basePolls =new CopyOnWriteArrayList<BasePoll>();
            List<BasePoll> olDbasePolls = PollingCache.getAllWebMap().putIfAbsent(userName, basePolls);
            if(olDbasePolls !=null){
                basePolls = olDbasePolls;
            }
        }
        basePolls.add(this);
        PollingCache.getAllWebMap().put(userName,basePolls);
        //如果不存在是，需要创建

    }
}
